# coding: utf-8
from datetime import datetime

import web

from libs import utils
from libs.utils import render, set_self_user, db


class tougao:
    @set_self_user
    def GET(self):

        return render('article/tougao', action=self)

    def POST(self):
        post = web.input()
        title = post.title
        content = post.content

        user_id = utils.get_user_id()
        create_time = utils.format_time1(datetime.now())

        article_id = db.insert('article', title=title, content=content, user_id=user_id, create_time=create_time)

        return web.seeother(f'/article/{article_id}')


class show:
    @set_self_user
    def GET(self, article_id):
        # 浏览量加1
        # todo 把article_id保存到cookie里面，如果上一个和当前的一样则不加1，目的是防刷量
        db.query('update article set views=views+1 where id=$article_id', vars={'article_id': article_id})

        article = db.select('article', where={'id': article_id})[0]

        article.content = utils.safe_html(article.content)

        user = utils.get_user(article.user_id)


        return render('article/show', action=self, article=article, user=user)
